package academic.emailClient.persistence;

import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.*;
import org.apache.lucene.util.Version;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Logger;

/** this class is designed to run only once at the beginning in order to generate index files under the Email Folders Index folder*/

public class IndexingFirstTime {

	private static FileReader fr ;
	private static IndexWriter writer;
	static BufferedReader buffer;
	private static File rootFolder; 
	private static File destFolder; 
	private static Iterator<File> files;
	private static Logger logger = Logger.getLogger(IndexingFirstTime.class.getName());
	private static String EMAIL_CLIENT_ROOT = "Email Folders";
	private static String EMAIL_CLIENT_INDEXING_ROOT = "Email Folders Index";
	
	/**
	 * initializing the values to index the files in the newly created folder Email Folders Index
	 * 
	 * @throws IOException
	 */
	
	static void initialize() throws IOException{
		
		rootFolder = new File(".", EMAIL_CLIENT_ROOT);	
		destFolder=new File(".", EMAIL_CLIENT_INDEXING_ROOT );
		Directory indexStorage = new SimpleFSDirectory(destFolder);
		writer = new IndexWriter(indexStorage,
				new StandardAnalyzer(Version.LUCENE_CURRENT),
				true, IndexWriter.MaxFieldLength.LIMITED);
		writer.setUseCompoundFile(false);
		files = FileUtils.iterateFiles(rootFolder, null, true);

	}

	public static void searchInFiles( File files) throws FileNotFoundException{

		String line="";
		String bodyMsgBuffer="";
		Document doc = new Document();
		File file = files;
		
		//Doing the indexing based on the criteria we chose 
		
		fr = new FileReader(file);
		buffer = new BufferedReader(fr);		   
		
		try{
			while ((line=buffer.readLine())!=null){
		
				String values[] = line.split("/");
				String v[]=values;
				
				if (values.length != 1){
					if ( values[0].equals("FROM"))
						doc.add(new Field("FROM",values[1],Field.Store.YES,Field.Index.NOT_ANALYZED));
					else if (values[0].equals("TO"))	
						doc.add(new Field("TO",values[1],Field.Store.YES,Field.Index.NOT_ANALYZED));
					else if (values[0].equals("SUBJECT"))
						doc.add(new Field("SUBJECT",values[1],Field.Store.YES,Field.Index.NOT_ANALYZED));
					else if (values[0].equals("BODY_MESSAGE"))
					{
						bodyMsgBuffer=values[1];
						line=buffer.readLine();
						v = line.split("/");
						while (! v[0].equals("DATE"))
						{
							bodyMsgBuffer=bodyMsgBuffer+" "+line;
							line=buffer.readLine();
							v = line.split("/");
						}
						doc.add(new Field("BODY_MESSAGE",bodyMsgBuffer,Field.Store.YES,Field.Index.NOT_ANALYZED));
					}
					values=v;
					if (values[0].equals("DATE"))
						doc.add(new Field("DATE",values[1],Field.Store.YES,Field.Index.NOT_ANALYZED));
					else if (values[0].equals("CC"))
						buffer.readLine();
				}//if
			}//while

			doc.add(new Field("PATH",file.getPath(),Field.Store.YES,Field.Index.NOT_ANALYZED));
			writer.addDocument(doc);
			buffer.close();
			fr.close();	

		}
		catch (IOException e) {
			System.err.println("Error: " + e);
		}

	}
	
	
	/**
	 * this method is an independent message run at the beginning to create the indexing of the whole 
	 * mails that we have .
	 * The indexing was based on the Recipient Email, Sender Email,Subject, the body message and the date.
	 * 
	 * and it's created once at the begin.
	 * 
	 * @throws IOException
	 */

	public static void main(String[] arg0){
		try {
			initialize();
			//got all the files in the main folder
			while( files.hasNext())
				searchInFiles(files.next());
			writer.optimize();
			writer.close();

		}
		catch (Exception e){
			System.err.println("Error: " + e);
		}
	}

	File getIndexFile(){
		if(this.destFolder.exists()){
			System.out.println(destFolder+"       ");
			return this.destFolder;}
		else{
			logger.severe("The Index file isn't created");
			return this.destFolder;
		}

	}


}//class



